#!/usr/bin/python
# -*- coding: utf-8 -*-

import GlobalVariable
from sqlalchemy import Column, String, create_engine, Integer
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

sleep_time = 3
# 创建对象的基类:
Base = declarative_base()


# 定义User对象:
class sampling_tab(Base):
    # 表的名字:
    __tablename__ = 'sampling'
    # 表的结构:
    mac = Column(String(20), primary_key=True)
    time = Column(Integer)
    upload = Column(Integer)
    download = Column(Integer)
    cpu = Column(Integer)
    mem = Column(Integer)


def in_sampling(data):
    # 初始化数据库连接:
    engine = create_engine(GlobalVariable.sqlservice, pool_timeout=30)
    # 创建DBSession类型:
    DBSession = sessionmaker(bind=engine)
    # 创建session对象:
    session = DBSession()
    mac, time, upload, download, cpu, mem = data
    # 创建新data对象:
    tab_data = sampling_tab(mac=mac, time=time, upload=upload, download=download, cpu=cpu, mem=mem)
    # 添加到session:
    session.add(tab_data)
    # 提交即保存到数据库:
    session.commit()
    # 关闭session:
    session.close()


class name_tab(Base):
    # 表的名字:
    __tablename__ = 'name'
    # 表的结构:
    device_id = Column(String(20), primary_key=True)
    device_name = Column(String(20))
    feed_id = Column(Integer)


def in_name(data):
    # 初始化数据库连接:
    engine = create_engine(GlobalVariable.sqlservice, pool_timeout=30)
    # 创建DBSession类型:
    DBSession = sessionmaker(bind=engine)
    # 创建session对象:
    session = DBSession()
    device_id, device_name, feed_id = data
    # 创建新data对象:
    tab_data = name_tab(device_id=device_id, device_name=device_name, feed_id=feed_id)
    # 添加到session:
    session.add(tab_data)
    # 提交即保存到数据库:
    session.commit()
    # 关闭session:
    session.close()


def delete_name():
    engine = create_engine(GlobalVariable.sqlservice, pool_timeout=30)
    # 创建DBSession类型:
    DBSession = sessionmaker(bind=engine)
    # 创建session对象:
    session = DBSession()
    for i in session.query(name_tab).all():
        session.delete(i)
        session.commit()
    session.close()


def find_name():
    feed_id_list = []
    engine = create_engine(GlobalVariable.sqlservice, pool_timeout=30)
    # 创建DBSession类型:
    DBSession = sessionmaker(bind=engine)
    # 创建session对象:
    session = DBSession()
    for i in session.query(name_tab).all():
        feed_id_list.append(i.feed_id)
        session.commit()
    session.close()
    return feed_id_list


if __name__ == "__main__":
    x = find_name()
    print(x)
